package com.haoxuer.discover.user.shiro.listener;

import com.haoxuer.discover.user.data.entity.UserBind;
import com.haoxuer.discover.user.data.entity.UserLoginLog;
import com.haoxuer.discover.user.data.enums.LoginState;
import com.haoxuer.discover.user.data.service.UserBindService;
import com.haoxuer.discover.user.data.service.UserLoginLogService;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component("userAuthenticationListener")
public class UserAuthenticationListener implements AuthenticationListener {

    @Autowired
    private UserLoginLogService logService;

    @Autowired
    private UserBindService bindService;

    @Override
    public void onSuccess(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo) {
        if (authenticationToken instanceof UsernamePasswordToken) {
            UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
            logService.save(token,LoginState.success);
        }

    }

    @Override
    public void onFailure(AuthenticationToken authenticationToken, AuthenticationException e) {
        if (authenticationToken instanceof UsernamePasswordToken) {
            UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
            logService.save(token,LoginState.fail);
        }
    }

    @Override
    public void onLogout(PrincipalCollection principalCollection) {
        System.out.println(principalCollection.getPrimaryPrincipal());
    }
}
